package jnpf.message.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import jnpf.base.UserInfo;
import jnpf.base.entity.MessageTemplateEntity;
import jnpf.base.entity.SmsTemplateEntity;
import jnpf.base.entity.SysConfigEntity;
import jnpf.base.service.MessageTemplateService;
import jnpf.base.service.SmsTemplateService;
import jnpf.base.service.SysconfigService;
import jnpf.base.util.SmsUtil;
import jnpf.constant.MsgCode;
import jnpf.message.entity.*;
import jnpf.message.enums.MessageTypeEnum;
import jnpf.message.model.message.DingTalkModel;
import jnpf.message.model.message.EmailModel;
import jnpf.message.model.message.SentMessageForm;
import jnpf.base.model.systemconfig.SmsModel;
import jnpf.message.model.sendmessageconfig.SendConfigTemplateModel;
import jnpf.message.service.*;
import jnpf.model.BaseSystemInfo;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 消息实体类
 *
 * @版本： V3.2.0
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2021/4/22 9:06
 */
@Component
@Slf4j
public class SentMessageUtil {

    @Autowired
    private UserService userService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private SysconfigService sysconfigService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private MessagereceiveService messagereceiveService;
    @Autowired
    private SynThirdInfoService synThirdInfoService;

    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private SmsTemplateService smsTemplateService;
    @Autowired
    private SendMessageConfigService sendMessageConfigService;

    @Autowired
    private SendConfigTemplateService sendConfigTemplateService;

    @Autowired
    private AccountConfigService accountConfigService;

    @Autowired
    private MessageTemplateConfigService messageTemplateConfigService;
    @Autowired
    private MessageMonitorService messageMonitorService;
    @Autowired
    private SmsFieldService smsFieldService;

    /**
     * 发送消息
     *
     * @param sentMessageForm
     */
    public void sendMessage(SentMessageForm sentMessageForm) {
        List<String> toUserIdsList = sentMessageForm.getToUserIds();
        // 模板id
        String templateId = sentMessageForm.getTemplateId();
        // 参数
        Map<String, Object> parameterMap = sentMessageForm.getParameterMap();
        UserInfo userInfo = sentMessageForm.getUserInfo();
        boolean flag = true;
        if (!(toUserIdsList != null && toUserIdsList.size() > 0)) {
            log.error("接收人员为空");
            flag = false;
        }
        if (StringUtil.isEmpty(templateId)) {
            log.error("模板Id为空");
            flag = false;
        }
        if (flag) {
            // 获取发送配置详情
//            MessageTemplateEntity entity = messageTemplateService.getInfo(templateId);
            SendMessageConfigEntity entity = sendMessageConfigService.getInfo(templateId);
            if(entity != null) {
                List<SendConfigTemplateEntity> list = sendConfigTemplateService.getDetailListByParentId(templateId);
                if(list != null && list.size()>0) {
                    for (SendConfigTemplateEntity entity1 : list) {
                        if ("1".equals(String.valueOf(entity1.getEnabledMark()))) {
                            String sendType = entity1.getMessageType();
                            MessageTypeEnum typeEnum = MessageTypeEnum.getByCode(sendType);
                            switch (typeEnum) {
                                case SysMessage:
                                    // 站内消息
                                    String content = sentMessageForm.getContent();
                                    Map<String, String> contentMsg = sentMessageForm.getContentMsg();
                                    MessageTemplateConfigEntity templateConfigEntity = messageTemplateConfigService.getInfo(entity1.getTemplateId());
                                    String title = sentMessageForm.getTitle();
                                    if (templateConfigEntity != null && !"1".equals(templateConfigEntity.getTemplateType())) {
                                        title = templateConfigEntity.getTitle();
                                        Map<String, Object> msgMap = new HashMap<>();
                                        msgMap = getParamMap(entity1.getId(),parameterMap);
                                        if (StringUtil.isNotEmpty(title)) {
                                            StringSubstitutor strSubstitutor = new StringSubstitutor(msgMap, "{", "}");
                                            title = strSubstitutor.replace(title);
                                        }
                                    }
                                    if(templateConfigEntity != null &&"1".equals(templateConfigEntity.getTemplateType())){
                                        title = templateConfigEntity.getTitle();
                                        title = title.replace("@流程发起人@流程名称"," "+sentMessageForm.getTitle());
                                    }
                                    messageService.sentMessage(toUserIdsList, title, content, contentMsg, userInfo);
                                    //消息监控写入
                                    MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
                                    monitorEntity.setId(RandomUtil.uuId());
                                    monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
                                    monitorEntity.setSendTime(DateUtil.getNowDate());
                                    monitorEntity.setCreatorTime(DateUtil.getNowDate());
                                    monitorEntity.setCreatorUserId(userInfo.getUserId());
                                    createMessageMonitor(monitorEntity, templateConfigEntity, null, null, userInfo, toUserIdsList, title);
                                    messageMonitorService.create(monitorEntity);
                                    break;
                                case SmsMessage:
                                    // 发送短信
                                    sendSms(toUserIdsList, entity1, parameterMap);
                                    break;
                                case MailMessage:
                                    // 邮件
                                    SendMail(toUserIdsList, userInfo, sendType, entity1, parameterMap);
                                    break;
                                case QyMessage:
                                    // 企业微信
                                    JSONObject jsonObject = SendQyWebChat(toUserIdsList, userInfo, sendType, entity1, parameterMap);
                                    if (!(Boolean) jsonObject.get("code")) {
                                        log.error("发送企业微信消息失败，错误：" + jsonObject.get("error"));
                                    }
                                    break;
                                case DingMessage:
                                    // 钉钉
                                    JSONObject jsonObject1 = SendDingTalk(toUserIdsList, userInfo, sendType, entity1, parameterMap);
                                    if (!(Boolean) jsonObject1.get("code")) {
                                        log.error("发送企业微信消息失败，错误：" + jsonObject1.get("error"));
                                    }
                                    break;
                                case WebHookMessage:
                                    // webhook
                                    SendWebHook(sendType, userInfo, entity1, parameterMap);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            else {
                String content = sentMessageForm.getContent();
                Map<String, String> contentMsg = sentMessageForm.getContentMsg();
                String title = sentMessageForm.getTitle();
                messageService.sentMessage(toUserIdsList, title, content, contentMsg, userInfo);
                //消息监控写入
                MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
                monitorEntity.setId(RandomUtil.uuId());
                monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
                monitorEntity.setSendTime(DateUtil.getNowDate());
                monitorEntity.setCreatorTime(DateUtil.getNowDate());
                monitorEntity.setCreatorUserId(userInfo.getUserId());
                createMessageMonitor(monitorEntity,null,null,null,userInfo,toUserIdsList,title);
                messageMonitorService.create(monitorEntity);
            }
        }
    }


    private void SendWebHook(String sendType, UserInfo userInfo, SendConfigTemplateEntity entity, Map<String, Object> parameterMap){
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(entity.getTemplateId());
        AccountConfigEntity accountEntity = accountConfigService.getInfo(entity.getAccountConfigId());
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        String content = msgTemEntity.getContent();
        //获取消息模板参数
        parameterMap = getParamMap(entity.getId(),parameterMap);
        // 替换参数
        if (StringUtil.isNotEmpty(content)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            content = strSubstitutor.replace(content);
        }
        String title = msgTemEntity.getTitle();
        if (StringUtil.isNotEmpty(title)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            title = strSubstitutor.replace(title);
        }
        //创建消息监控
        monitorEntity = createMessageMonitor(monitorEntity,msgTemEntity,accountEntity,content,userInfo,null,title);
        if(entity != null) {
            if(accountEntity != null) {
                switch (accountEntity.getWebhookType()) {
                    case "1":
                        //钉钉
                        if ("1".equals(accountEntity.getApproveType())) {
                            WebHookUtil.sendDDMessage(accountEntity.getWebhookAddress(), content);
                            messageMonitorService.create(monitorEntity);
                        } else if ("2".equals(accountEntity.getApproveType())) {
                            WebHookUtil.sendDingDing(accountEntity.getWebhookAddress(), accountEntity.getBearer(), content);
                            messageMonitorService.create(monitorEntity);
                        }
                        break;
                    case "2":
                        if ("1".equals(accountEntity.getApproveType())) {
                            WebHookUtil.callWeChatBot(accountEntity.getWebhookAddress(), content);
                            messageMonitorService.create(monitorEntity);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 发送企业微信消息
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    private JSONObject SendQyWebChat(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(entity.getTemplateId());
        AccountConfigEntity accountEntity = accountConfigService.getInfo(entity.getAccountConfigId());
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        JSONObject retJson = new JSONObject();
        if(msgTemEntity != null) {
            // 替换参数
            String content = msgTemEntity.getContent();
            //获取消息模板参数
            parameterMap = getParamMap(entity.getId(),parameterMap);
            // 替换参数
            if (StringUtil.isNotEmpty(content)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                content = strSubstitutor.replace(content);
            }
            String title = msgTemEntity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }
            // 获取系统配置
            if(accountEntity != null) {
                Map<String, String> objModel = new HashMap<>();
                objModel.put("qyhCorpId", accountEntity.getEnterpriseId());
                objModel.put("qyhAgentId", accountEntity.getAppId());
                objModel.put("qyhAgentSecret", accountEntity.getAppSecret());
//                Map<String, String> objModel = getSystemConfig();
                BaseSystemInfo config = JsonUtil.getJsonToBean(objModel, BaseSystemInfo.class);
                String corpId = config.getQyhCorpId();
                String agentId = config.getQyhAgentId();
                // 获取的应用的Secret值
                String corpSecret = config.getQyhAgentSecret();
                String wxUserId = "";
                StringBuilder toWxUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();

                // 相关参数验证
                if (StringUtil.isEmpty(corpId)) {
                    log.error("企业ID为空");
                    retJson.put("code", false);
                    retJson.put("error", "企业ID为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(corpSecret)) {
                    retJson.put("code", false);
                    retJson.put("error", "Secret为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(agentId)) {
                    retJson.put("code", false);
                    retJson.put("error", "AgentId为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(content)) {
                    retJson.put("code", false);
                    retJson.put("error", "内容为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (toUserIdsList == null || toUserIdsList.size() < 1) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));
                //创建消息监控
                monitorEntity = createMessageMonitor(monitorEntity,msgTemEntity,accountEntity,content,userInfo,toUserIdsList,title);
                // 获取接收人员的企业微信号、创建消息用户实体
                for (String userId : toUserIdsList) {
                    wxUserId = "";
                    // 从同步表获取对应的企业微信ID
                    SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoBySysObjId("1", "2", userId);
                    if (synThirdInfoEntity != null) {
                        wxUserId = synThirdInfoEntity.getThirdObjId();
                    }
                    if (StringUtil.isEmpty(wxUserId)) {
                        nullUserInfo = nullUserInfo.append(",").append(userId);
                    } else {
                        toWxUserId = toWxUserId.append("|").append(wxUserId);
                    }
                    messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
                }

                // 处理企业微信号信息串并验证
                toUserIdAll = toWxUserId.toString();
                if (StringUtil.isNotEmpty(toUserIdAll)) {
                    toUserIdAll = toUserIdAll.substring(1);
                }
                if (StringUtil.isEmpty(toUserIdAll)) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人对应的企业微信号全部为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 批量发送企业信息信息
                retJson = QyWebChatUtil.sendWxMessage(corpId, corpSecret, agentId, toUserIdAll, content);
                messageMonitorService.create(monitorEntity);
                if (!retJson.getBoolean("code")) {
                    return retJson;
                }

                // 企业微信号为空的信息写入备注
                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                    messageEntity.setDescription(nullUserInfo.substring(1) + "对应的企业微信号为空");
                }
                // 写入系统的消息表、消息用户表
            }else {
                retJson.put("code", false);
                retJson.put("error", "账号配置数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * List<String> toUserIdsList, UserInfo userInfo, String sendType, MessageTemplateEntity entity, Map<String, String> parameterMap
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    private JSONObject SendDingTalk(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(entity.getTemplateId());
        AccountConfigEntity accountEntity = accountConfigService.getInfo(entity.getAccountConfigId());
        //消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        JSONObject retJson = new JSONObject();
        if(msgTemEntity != null) {
            String content = msgTemEntity.getContent();
            //获取消息模板参数
            parameterMap = getParamMap(entity.getId(),parameterMap);
            // 替换参数
            if (StringUtil.isNotEmpty(content)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                content = strSubstitutor.replace(content);
            }
            String title = msgTemEntity.getTitle();
            if (StringUtil.isNotEmpty(title)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                title = strSubstitutor.replace(title);
            }

            if (accountEntity != null) {
                Map<String, String> objModel = new HashMap<>();
                objModel.put("dingSynAppKey", accountEntity.getAppId());
                objModel.put("dingSynAppSecret", accountEntity.getAppSecret());
                objModel.put("dingAgentId", accountEntity.getAgentId());
                DingTalkModel dingTalkModel = JsonUtil.getJsonToBean(objModel, DingTalkModel.class);
                String appKey = dingTalkModel.getDingSynAppKey();
                String appSecret = dingTalkModel.getDingSynAppSecret();
                String agentId = dingTalkModel.getDingAgentId();
                String dingUserId = "";
                StringBuilder toDingUserId = new StringBuilder();
                String toUserIdAll = "";
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();

                // 相关参数验证
                if (StringUtil.isEmpty(appKey)) {
                    retJson.put("code", false);
                    retJson.put("error", "AppKey为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(appSecret)) {
                    retJson.put("code", false);
                    retJson.put("error", "AppSecret为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(agentId)) {
                    retJson.put("code", false);
                    retJson.put("error", "AgentId为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (StringUtil.isEmpty(content)) {
                    retJson.put("code", false);
                    retJson.put("error", "内容为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }
                if (toUserIdsList == null || toUserIdsList.size() < 1) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 创建消息实体
                MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), content, null, Integer.parseInt(sendType));
                //创建消息监控
                monitorEntity = createMessageMonitor(monitorEntity,msgTemEntity,accountEntity,content,userInfo,toUserIdsList,title);
                // 获取接收人员的钉钉号、创建消息用户实体
                for (String userId : toUserIdsList) {
                    dingUserId = "";
                    // 从同步表获取对应用户的钉钉ID
                    SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoBySysObjId("2", "2", userId);
                    if (synThirdInfoEntity != null) {
                        dingUserId = synThirdInfoEntity.getThirdObjId();
                    }
                    if (StringUtil.isEmpty(dingUserId)) {
                        nullUserInfo = nullUserInfo.append(",").append(userId);
                    } else {
                        toDingUserId = toDingUserId.append(",").append(dingUserId);
                    }
                    messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
                }

                // 处理接收人员的钉钉号信息串并验证
                toUserIdAll = toDingUserId.toString();
                if (StringUtil.isNotEmpty(toUserIdAll)) {
                    toUserIdAll = toUserIdAll.substring(1);
                }
                if (StringUtil.isEmpty(toUserIdAll)) {
                    retJson.put("code", false);
                    retJson.put("error", "接收人对应的钉钉号全部为空");
                    messageMonitorService.create(monitorEntity);
                    return retJson;
                }

                // 批量发送钉钉信息
                retJson = DingTalkUtil.sendDingMessage(appKey, appSecret, agentId, toUserIdAll, content);
                messageMonitorService.create(monitorEntity);
                if (!retJson.getBoolean("code")) {
                    return retJson;
                }

                // 钉钉号为空的信息写入备注
                if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                    messageEntity.setDescription(nullUserInfo.toString().substring(1) + "对应的钉钉号为空");
                }
                // 写入系统的消息表、消息用户表
            }else {
                retJson.put("code", false);
                retJson.put("error", "消息模板数据不存在");
                messageMonitorService.create(monitorEntity);
                return retJson;
            }
        }else {
            retJson.put("code", false);
            retJson.put("error", "消息模板数据不存在");
            messageMonitorService.create(monitorEntity);
            return retJson;
        }
        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * 发送邮件
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    private void SendMail(List<String> toUserIdsList, UserInfo userInfo, String sendType, SendConfigTemplateEntity entity, Map<String, Object> parameterMap) {
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(entity.getTemplateId());
        AccountConfigEntity accountEntity = accountConfigService.getInfo(entity.getAccountConfigId());
        //消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        if(msgTemEntity != null) {
            if(accountEntity != null) {
                // 获取系统配置
                Map<String, String> objModel = new HashMap<>();
                objModel.put("emailSmtpHost", accountEntity.getSmtpServer());
                objModel.put("emailSmtpPort", accountEntity.getSmtpPort().toString());
                objModel.put("emailSenderName", accountEntity.getAddressorName());
                objModel.put("emailAccount", accountEntity.getSmtpUser());
                objModel.put("emailPassword", accountEntity.getSmtpPassword());

                EmailModel emailModel = JsonUtil.getJsonToBean(objModel, EmailModel.class);
                StringBuilder nullUserInfo = new StringBuilder();
                List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();
                StringBuilder toUserMail = new StringBuilder();
                String userEmailAll = "";
                String userEmail = "";
                String userName = "";

                // 相关参数验证
                if (StringUtil.isEmpty(emailModel.getEmailSmtpHost())) {
                    log.error("SMTP服务为空");
                    messageMonitorService.create(monitorEntity);
                } else if (StringUtil.isEmpty(emailModel.getEmailSmtpPort())) {
                    log.error("SMTP端口为空");
                    messageMonitorService.create(monitorEntity);
                } else if (StringUtil.isEmpty(emailModel.getEmailAccount())) {
                    log.error("发件人邮箱为空");
                    messageMonitorService.create(monitorEntity);
                } else if (StringUtil.isEmpty(emailModel.getEmailPassword())) {
                    log.error("发件人密码为空");
                    messageMonitorService.create(monitorEntity);
                } else if (toUserIdsList == null || toUserIdsList.size() < 1) {
                    log.error("接收人为空");
                    messageMonitorService.create(monitorEntity);
                } else {
                    parameterMap = getParamMap(entity.getId(),parameterMap);
                    // 设置邮件标题
                    String title = msgTemEntity.getTitle();
                    if (StringUtil.isNotEmpty(title)) {
                        StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                        title = strSubstitutor.replace(title);
                    }
                    emailModel.setEmailTitle(title);
                    // 设置邮件内容
                    String content = msgTemEntity.getContent();
                    //获取消息模板参数
                    if (StringUtil.isNotEmpty(content)) {
                        StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
                        content = strSubstitutor.replace(content);
                    }
                    emailModel.setEmailContent(content);

                    // 创建消息实体
                    MessageEntity messageEntity = JnpfMessageUtil.setMessageEntity(userInfo.getUserId(), title, emailModel.getEmailContent(), Integer.parseInt(sendType));
                    //创建消息监控
                    monitorEntity = createMessageMonitor(monitorEntity,msgTemEntity,accountEntity,content,userInfo,toUserIdsList,title);
                    // 获取收件人的邮箱地址、创建消息用户实体
                    for (String userId : toUserIdsList) {
                        UserEntity userEntity = userService.getInfo(userId);
                        if (userEntity != null) {
                            userEmail = StringUtil.isEmpty(userEntity.getEmail()) ? "" : userEntity.getEmail();
                            userName = userEntity.getRealName();
                        }
                        if (userEmail != null && !"".equals(userEmail)) {
                            if(EmailUtil.isEmail(userEmail)) {
                                toUserMail = toUserMail.append(",").append(userName).append("<").append(userEmail).append(">");
                            }
                        } else {
                            nullUserInfo = nullUserInfo.append(",").append(userId);
                        }
                        messageReceiveList.add(JnpfMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
                    }

                    // 处理接收人员的邮箱信息串并验证
                    userEmailAll = toUserMail.toString();
                    if (StringUtil.isNotEmpty(userEmailAll)) {
                        userEmailAll = userEmailAll.substring(1);
                    }
                    if (StringUtil.isEmpty(userEmailAll)) {
                        log.error("全部接收人对应的邮箱格式错误");
                        messageMonitorService.create(monitorEntity);
                    } else {
                        // 设置接收人员
                        emailModel.setEmailToUsers(userEmailAll);
                        // 发送邮件
                        JSONObject retJson = EmailUtil.sendMail(emailModel);
                        messageMonitorService.create(monitorEntity);
                        if (!retJson.getBoolean("code")) {
                            log.error("发送失败");
                        } else {
                            // 邮箱地址为空的信息写入备注
                            if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
                                messageEntity.setDescription(nullUserInfo.substring(1) + "对应的邮箱为空");
                            }
                            // 写入系统的消息表、消息用户表
                        }
                    }
                }
            }
        }
    }

    /**
     * 发送短信
     *
     * @param toUserIdsList
     * @param entity
     * @param parameterMap
     * @return
     */
    private void sendSms(List<String> toUserIdsList, SendConfigTemplateEntity entity, Map<String, Object> parameterMap) {
        UserInfo userInfo = userProvider.get();
        //获取短信配置
        AccountConfigEntity accountEntity = accountConfigService.getInfo(entity.getAccountConfigId());
        // 获取消息模板详情
        MessageTemplateConfigEntity msgTemEntity = messageTemplateConfigService.getInfo(entity.getTemplateId());
        //消息监控
        MessageMonitorEntity monitorEntity = new MessageMonitorEntity();
        monitorEntity.setId(RandomUtil.uuId());
        monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        monitorEntity.setSendTime(DateUtil.getNowDate());
        monitorEntity.setCreatorTime(DateUtil.getNowDate());
        monitorEntity.setCreatorUserId(userInfo.getUserId());
        if (accountEntity != null) {
            //账号配置——短信
            Map<String, String> objModel = new HashMap<>(16);
            objModel.put("aliAccessKey", accountEntity.getAppId());
            objModel.put("aliSecret", accountEntity.getAppSecret());
            objModel.put("tencentSecretId", accountEntity.getAppId());
            objModel.put("tencentSecretKey", accountEntity.getAppSecret());
            objModel.put("tencentAppId", accountEntity.getSdkAppId());
            objModel.put("tencentAppKey", accountEntity.getAppKey());
            SmsModel smsConfig = JsonUtil.getJsonToBean(objModel, SmsModel.class);
            int company = Integer.parseInt(accountEntity.getChannel());
            // 组装接受用户
            StringBuffer toUserIdList = new StringBuffer();
            for (String toUserId : toUserIdsList) {
                UserEntity userEntity = userService.getInfo(toUserId);
                if(isPhone(userEntity.getMobilePhone())) {
                    toUserIdList.append(userEntity.getMobilePhone() + ",");
                }
            }
            if(StringUtil.isEmpty(toUserIdList)){
                log.error("全部接收人对应的手机号码格式错误");
                messageMonitorService.create(monitorEntity);
            }
            //获取消息模板参数
            parameterMap = getParamMap(entity.getId(),parameterMap);
            //短信参数
            Map<String, Object> smsMap = new HashMap<>();
            if (entity != null) {
                smsMap = smsFieldService.getParamMap(entity.getTemplateId(), parameterMap);
            }

            if (msgTemEntity != null) {
                String endPoint = "";
                if("1".equals(accountEntity.getChannel())){
                    endPoint = accountEntity.getEndPoint();
                }else if("2".equals(accountEntity.getChannel())){
                    endPoint = accountEntity.getZoneName();
                }
                SmsUtil.sentSms(company, smsConfig, endPoint, accountEntity.getZoneParam(), toUserIdList.toString(), accountEntity.getSmsSignature(), msgTemEntity.getTemplateCode(), smsMap);
                String content = SmsUtil.querySmsTemplateContent(company, smsConfig, endPoint, accountEntity.getZoneParam(), msgTemEntity.getTemplateCode());
                if(StringUtil.isNotBlank(content) && !"null".equals(content)) {
                    if(ObjectUtil.isNotEmpty(smsMap) && !"null".equals(smsMap)) {
                        if ("1".equals(accountEntity.getChannel())) {
                            if (content.contains("${")) {
                                for (String key : smsMap.keySet()) {
                                    content = content.replace("${" + key + "}", smsMap.get(key).toString());
                                }
                            }
                        } else if ("2".equals(accountEntity.getChannel())) {
                            if (content.contains("{")) {
                                for (String key : smsMap.keySet()) {
                                    content = content.replace("{" + key + "}", smsMap.get(key).toString());
                                }
                            }
                        }
                    }
                }
                //创建消息监控
                monitorEntity = createMessageMonitor(monitorEntity,msgTemEntity,accountEntity,content,userInfo,toUserIdsList,null);
                messageMonitorService.create(monitorEntity);
            }else {
                log.error("消息模板数据不存在");
                messageMonitorService.create(monitorEntity);
            }
        }else {
            log.error("账号配置数据不存在");
            messageMonitorService.create(monitorEntity);
        }
    }

    /**
     * 获取系统配置
     */
    private Map<String, String> getSystemConfig() {
        // 获取系统配置
        List<SysConfigEntity> configList = sysconfigService.getList("SysConfig");
        Map<String, String> objModel = new HashMap<>(16);
        for (SysConfigEntity entity : configList) {
            objModel.put(entity.getFkey(), entity.getValue());
        }
        return objModel;
    }

    private Map<String,Object> getParamMap(String templateId, Map<String,Object> paramMap){
        Map<String,Object> map = new HashMap<>();
        for(String key:paramMap.keySet()){
            if(key.contains(templateId)){
                map.put(key.substring(templateId.length()),paramMap.get(key));
            }
        }
        return map;
    }

    private MessageMonitorEntity createMessageMonitor(MessageMonitorEntity monitorEntity,MessageTemplateConfigEntity msgTemEntity,AccountConfigEntity accountEntity,String content,UserInfo userInfo,List<String> toUserIdsList,String title){
        if(msgTemEntity != null){
            monitorEntity.setMessageTemplateId(msgTemEntity.getId());
            monitorEntity.setMessageSource(msgTemEntity.getMessageSource());
            if(StringUtil.isNotBlank(title)){
                monitorEntity.setTitle(title);
            }else {
                monitorEntity.setTitle(msgTemEntity.getTitle());
            }
            monitorEntity.setMessageType(msgTemEntity.getMessageType());
        }else {
            if(StringUtil.isNotBlank(title)) {
                monitorEntity.setTitle(title);
            }
            monitorEntity.setMessageType("1");
        }
        if(accountEntity != null){
            monitorEntity.setAccountId(accountEntity.getId());
            monitorEntity.setAccountCode(accountEntity.getEnCode());
            monitorEntity.setAccountName(accountEntity.getFullName());
        }
        if("6".equals(msgTemEntity.getMessageType()) && accountEntity != null) {
            monitorEntity.setReceiveUser(accountEntity.getWebhookAddress());
        }else {
            monitorEntity.setReceiveUser(JsonUtil.getObjectToString(toUserIdsList));
        }
        monitorEntity.setContent(content);
        return monitorEntity;
    }

    public static boolean isPhone(String phone){
        if (StringUtil.isNotBlank(phone) && !"null".equals(phone)) {
            return Pattern.matches("^1[3-9]\\d{9}$", phone);
        }
        return false;
    }

}
